<template>
  <div>
    <div style="text-align: center; margin: 10px">
      <el-input
        v-model="newAlarm"
        placeholder="请输入新的报警"
        size="small"
        style="width: 600px"
      />
      <el-button
        style="margin-left: 10px"
        type="primary"
        icon="el-icon-edit"
        size="small"
        @click="handleCreate"
      >
        确认新增
      </el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column
        label="序号"
        type="index"
        width="100"
        align="center"
      />
      <el-table-column prop="item" label="报警" align="center" />
      <el-table-column
        label="操作"
        align="center"
        width="210"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{ row, $index }">
          <el-button
            type="danger"
            size="mini"
            plain
            @click="handleDelete(row.id, $index)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import { getAlarms, setAlarm, delAlarm } from '@/api/txs'

export default {
  data () {
    return {
      list: null,
      listLoading: true,
      newAlarm: ''
    }
  },
  // computed: {
  //   ...mapGetters([
  //     'name'
  //   ])
  // },
  created () {
    this.fetchData()
  },
  methods: {
    fetchData () {
      this.listLoading = true
      getAlarms().then(res => {
        this.list = res.data.data
        this.listLoading = false
      })
    },
    handleCreate () {
      if (this.newAlarm === '') {
        this.$alert('请先填入报警信息', '警告', {
          type: 'warning',
          confirmButtonText: '确定'
        })
      } else {
        setAlarm({ item: this.newAlarm }).then(res => {
          console.log(res.data)
          const d = res.data.data
          this.list.unshift(d)
          this.$notify({
            title: res.data.message,
            message: res.data.status,
            type: 'success',
            duration: 2000
          })
        })
      }
    },
    handleDelete (id, index) {
      this.$confirm('确定要删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          delAlarm(id).then(() => {
            this.$notify({
              title: 'Success',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
          })
          this.list.splice(index, 1)
        })
        .catch(() => {})
    }
  }
}
</script>
